package com.clas.liu.myapplication.model.impl;

import android.os.Handler;
import android.os.Message;

import com.clas.liu.myapplication.model.event.BaseEvent;
import com.clas.liu.myapplication.network.NetworkInterfaces;

/**
 * Model的基类
 * 子类需实现IBaseModel接口
 * 因为是异步的，没有直接调用presenter的方法，通过handler
 * Created by liu on 2019/2/27.
 */

public abstract class BaseModel {

    NetworkInterfaces interfaces;
    private Handler mHandler;

    public BaseModel(Handler handler){
        this.mHandler = handler;
        this.interfaces = getNetworkInterface();
    }

    /**
     * 同步，虽然只有一个activity调用一个postEvent，但是存在
     * 同一个activity下多个线程同时给主线程发送消息请求数据的传递
     * @param event 包含网络请求的what和obj
     */
    synchronized void postEvent(BaseEvent event){
        if (mHandler !=null){
            Message message = mHandler.obtainMessage();
            message.what = event.getWhat();
            message.obj = event;
            mHandler.sendMessage(message);
        }

    }

    protected abstract NetworkInterfaces getNetworkInterface();

    /**
     * avtivity销毁的时候必须销毁对其handler的引用
     */
    public void onDestroy(){
        mHandler = null;
    }
}
